package com.project.platform.interceptor;

import com.alibaba.fastjson2.JSON;
import com.project.platform.dto.CurrentUserDTO;
import com.project.platform.exception.CustomException;
import com.project.platform.utils.CurrentUserThreadLocal;
import com.project.platform.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long startTime = System.currentTimeMillis();
        request.setAttribute("requestStartTime", startTime);
        
        // OPTIONS请求不做校验
        if (request.getMethod().toUpperCase().equals("OPTIONS")) {
            return true;
        }
        
        // 获取header的token参数
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            log.warn("token为空，请求被拦截: {}", request.getRequestURL());
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        
        try {
            Claims claims = JwtUtils.verifyJwt(token);
            if (claims == null) {
                log.warn("token无效，请求被拦截: {}", request.getRequestURL());
                throw new CustomException(HttpStatus.UNAUTHORIZED, "token无效，请重新登录");
            }
            
            // 检查token是否过期
            if (claims.getExpiration() != null && claims.getExpiration().before(new Date())) {
                log.warn("token已过期，请求被拦截: {}", request.getRequestURL());
                throw new CustomException(HttpStatus.UNAUTHORIZED, "token已过期，请重新登录");
            }
            
            CurrentUserDTO currentUserDTO = JSON.parseObject(claims.get("currentUser").toString(), CurrentUserDTO.class);
            CurrentUserThreadLocal.set(currentUserDTO);
            return true;
        } catch (Exception e) {
            log.warn("token验证失败: {}, 错误: {}", request.getRequestURL(), e.getMessage());
            throw new CustomException(HttpStatus.UNAUTHORIZED, "token验证失败，请重新登录");
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 只在调试模式下记录耗时
        if (log.isDebugEnabled()) {
            long startTime = (Long) request.getAttribute("requestStartTime");
            log.debug("LoginInterceptor 结束 耗时：{} ms", System.currentTimeMillis() - startTime);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentUserThreadLocal.clear();
        // 移除不必要的日志输出
    }
}
